<template>
	<el-card class="box-card table">
		<template #header>
			<div class="card-header">
				<span>
					<el-breadcrumb separator="/">
						<el-breadcrumb-item :to="{ path: '/product/list' }">商品列表</el-breadcrumb-item>
						<el-breadcrumb-item>编辑</el-breadcrumb-item>
					</el-breadcrumb>
				</span>
				<router-link :to="{ path: '/product/list' }">
					<el-button class="button" type="success" icon="el-icon-back" size="small">返回</el-button>
				</router-link>
			</div>
		</template>
		<div class="body">
			<el-form :model="form" ref="form" status-icon :rules="rules" label-width="100px" size="small">
				<el-form-item label="商品名称" prop="name">
					<el-input v-model="form.name" placeholder="请输入商品名称"></el-input>
				</el-form-item>


				<el-form-item label="商品图片" prop="image">
					<div class="productImage">
						<uploadSingle @getImageUrl="getImageUrl" :imageUrl="form.image"></uploadSingle>
					</div>
				</el-form-item>

				<el-form-item label="商品分类" prop="category_id">
					<div class="product_category">
						<el-select v-model="form.category_id" placeholder="请选择商品分类" style="width: 100%">
							<el-option v-for="item in options" :key="item.value" :label="item.label"
								:value="item.value"></el-option>
						</el-select>
					</div>
				</el-form-item>

				<el-form-item label="商品单价" prop="price">
					<el-input v-model="form.price" type="number" min="0" step="0.01" placeholder="请输入商品单价">
						<template slot="append">元</template>
					</el-input>
				</el-form-item>

				<el-form-item label="库存数量" prop="stock_quantity">
					<el-input v-model="form.stock_quantity" type="number" min="0" placeholder="请输入库存数量"></el-input>
				</el-form-item>

				<el-form-item>
					<el-button type="primary" @click="submitForm('form')">保存修改</el-button>
					<el-button @click="resetForm('form')">重置</el-button>
				</el-form-item>
			</el-form>
		</div>
	</el-card>
</template>

<script>
	import {
		productShow,
		productSave,
		getCategorySelect
	} from "@/api/index.js";
	import uploadSingle from "@/components/UploadSingle.vue"

	export default {
		name: "ProductEdit",
		components: {
			uploadSingle
		},
		data() {
			return {
				debugMode: process.env.NODE_ENV === 'development', // 开发模式显示调试信息
				options: [],
				form: {
					id: "",
					name: "",
					image: "",
					category_id: "",
					price: "",
					stock_quantity: "",
				},
				rules: {
					name: [{
						required: true,
						message: "请输入商品名称",
						trigger: "blur"
					}],
					image: [{
						required: true,
						message: "请上传商品图片",
						trigger: "blur"
					}],
					category_id: [{
						required: true,
						message: "请选择商品分类",
						trigger: "change"
					}],
					price: [{
						required: true,
						message: "请输入商品单价",
						trigger: "blur"
					}, {
						validator: (rule, value, callback) => {
							if (value < 0) {
								callback(new Error('单价不能为负数'));
							} else {
								callback();
							}
						},
						trigger: 'blur'
					}],
					stock_quantity: [{
						required: true,
						message: "请输入商品库存数量",
						trigger: "blur"
					}, {
						validator: (rule, value, callback) => {
							if (value < 0) {
								callback(new Error('库存数量不能为负数'));
							} else {
								callback();
							}
						},
						trigger: 'blur'
					}],
				},
			};
		},
		created() {
			this.getInit();
			this.getCategorySelect();
		},
		methods: {
			async getInit() {
				const id = this.$route.query.id;
				if (!id) {
					this.$message.error("商品ID不存在");
					this.$router.push('/product/list');
					return;
				}

				try {
					const res = await productShow({
						id: id
					});
					if (res.code == 1) {
						this.form = {
							...res.data
						};
						console.log('获取到的商品数据:', res.data);
					} else {
						this.$message.error("获取商品信息失败");
						this.$router.push('/product/list');
					}
				} catch (error) {
					console.error('获取商品详情失败:', error);
					this.$message.error("获取商品信息失败");
					this.$router.push('/product/list');
				}
			},

			async submitForm(formName) {
				try {
					// 表单验证
					const valid = await this.$refs[formName].validate();
					if (!valid) {
						return false;
					}

					console.log('提交的数据:', this.form);

					const res = await productSave(this.form);
					console.log('保存响应:', res);

					if (res.code == 1) {
						this.$message.success('修改成功');
						this.$router.push('/product/list');
					} else {
						this.$message.error(res.message || '修改失败');
					}
				} catch (error) {
					console.error('表单验证或保存失败:', error);
					if (error && error.fields) {
						this.$message.error('请完善表单信息');
					}
				}
			},

			resetForm(formName) {
				this.$confirm('确定要重置表单吗？所有修改将丢失。', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					// 重置为原始数据
					this.getInit();
					this.$message.info('重置成功');
				}).catch(() => {
					// 用户取消重置
				});
			},

			getImageUrl(ImageUrl) {
				console.log('接收到图片URL:', ImageUrl);
				this.form.image = ImageUrl;

				// 手动触发表单验证
				this.$nextTick(() => {
					this.$refs.form.validateField('image');
				});
			},

			async getCategorySelect() {
				try {
					const result = await getCategorySelect();
					if (result.code == 1) {
						this.options = result.data;
					} else {
						this.$message.error('获取分类列表失败');
					}
				} catch (error) {
					console.error('获取分类列表失败:', error);
					this.$message.error('获取分类列表失败');
				}
			}
		}
	};
</script>

<style scoped>
	.body {
		padding: 20px;
		max-width: 600px;
	}

	.productImage {
		text-align: left;
	}

	.product_category {
		text-align: left;
	}

	.card-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.box-card {
		margin: 20px;
	}

	.el-form-item {
		margin-bottom: 22px;
	}

	.el-button {
		margin-right: 10px;
	}
</style>